/*
 * HtmlWrapper.cpp
 *
 *  Created on: 18.01.2013
 *      Author: sebastian
 */

#include <iostream>

#include <cstdlib>

#include "HtmlWrapper.h"
#include "utils/utils.h"
#include "utils/HtmlTools.h"

#include "Game/World/Universe.h"
#include "Server/Server.h"


using namespace std;

Body HtmlWrapper::getLoginPage() {
	//send loginpage

	string fileName = PATHTOSHARE;
	fileName += "login.html"; //TODO looks ugly....


	return fileToStr(fileName, true);
}

Response HtmlWrapper::login(const string &request, const string &clientIP) {
	Header header = "";
	Body   body   = "";


	//low: postrequests are till now reserved for login.... change this?!
	string user = getValue(request, "user");
	string pass = getValue(request, "pass");

	//if combination is correct, set sessid-Cookie and refer to home.html
	if (g_pGame->login(user, pass, clientIP)) {
		mLog(user + " logged in");
		body = "<html><header><meta http-equiv='Refresh' content='0; URL=/home.html' /></header>"
				"<body><h1>erfolgreich eingeloggt! - Sie werden automatisch Weitergeleitet"
				"</h1><a href='home.html'>weiter!</a></body></html>";
		header = "HTTP/1.0 200 OK\nContent-Type: text/html\nSet-Cookie: mindFuckSessID=";
		//low: put cookiename in define/config file
		header += intToStr( g_pGame->getPlayerByName(user)->getSessionID() );
		header +="\nContent-Length: "+intToStr(body.length());
	} else {

		body = "<html><body>du opfer hast deinen usernamen/passwort vergessen ... HAHA! <br /> "
				"   ...solltest du dich nur vertippt haben - HAHA! "
				"<a href='login.html'>Zurück</a></body></html>";
		header = Server::generateNormalHeader(body.length());
	}
	return (header+"\n\n"+body);
}

Body HtmlWrapper::getTime() {
	return intToStr(g_pGame->getTime());
}

Body HtmlWrapper::getHomePage(const Player *player) {
	//send home.html
	string fileName = PATHTOSHARE;
	fileName += "home.html";

	return fileToStr(fileName, true);
}

Body HtmlWrapper::getJQuery() {
	Body body = "";
	//low: get jquery from jquery.com via scriptlink in html file?
	string fileName = PATHTOSHARE;
#ifdef DEBUG
	fileName += "jquery-1.9.0.js";
#else
	fileName += "jquery-1.9.0.min.js";
#endif

	return fileToStr(fileName, true);
}

Body HtmlWrapper::getThreeJS() {
	Body body = "";
	//low: use compressed version when not in debug mode?:
	string fileName = PATHTOSHARE;

	fileName += "three.js";


	return fileToStr(fileName, true);
}



Body HtmlWrapper::getMap() {
	string fileName = PATHTOSHARE;
	fileName += "map.html";

	return fileToStr(fileName, true);
}

Body HtmlWrapper::getSpaceships(const Player *player) {
	return "stub"; //TODO
}

Body HtmlWrapper::getSettings(const Player *player) {
	return "stub"; //TODO
}

Body HtmlWrapper::getPlanets(const Player *player) {
	string res = "";
	res += g_phTls->generateTableHead();
	res += g_phTls->generateRow("ID", "Name", "X", "Y", "Z");
	for (Planet* it : player->getPlanets())
	{
		// cpp11 rocks ftw!
		Vec coord= it->getPos();
		res += g_phTls->generateRow(it->getpId(), it->getName(), coord.getX(), coord.getY(), coord.getZ());
	}
	res += g_phTls->generateTableFoot();
	return "stub"; //TODO
}

Body HtmlWrapper::getUniverse() {
	DmLog("sending universe...");
	return g_pGame->getUniverse()->toString();
}

/**
 *  This Function does:
 *
 * 0. decide whether playerdata needs to be extracted...
 * 1. figure out which player it is...
 * 2. call the players specified action in form player[id....].doWhatever(with whatever)
 * 3. "pipe" response of player-funciton-call to serveroutput
 *
 */
string HtmlWrapper::processRequest(const string &request, const std::string &clientIP) {
	Body   body   = "";
	Header header = "";

	//cout << "\nRequest:" << request << '\n'; //only for debug

	DmLog("processing request from Host: " + clientIP);
	//DmLog("---- Request:    ----\n" + request + "---- Request End ----\n");


	//detect username and pw if POST request....
	if (request.find("POST") != string::npos) {
		header = login(request, clientIP);
	} else {
		if (request.find("time.html") != string::npos) {
			body = getTime();
		} else if (request.find("jquery.js") != string::npos) {
			body = getJQuery();
		} else if (request.find("three.js") != string::npos) {
			body = getThreeJS();
		} else if (request.find("universe.json") != string::npos) {
			body = getUniverse();
		} else{

			//test whether player is logged in.
			Player * player = g_pGame->getPlayerBySessionID(atoi(getValue(request, "mindFuckSessID").c_str()));
			//if logged in, player with this sessid exists
			if (player != NULL) {
				DmLog("Player "+player->getName()+" is loggedin.");
				//TODO give it more sense! don't always answer with home.html
				if (request.find("map.html") != string::npos) {
					body = getMap();
				} else if (request.find("planets.html") != string::npos) {
					body = getPlanets(player);
				} else if (request.find("spaceships.html") != string::npos) {
					body = getSpaceships(player);
				} else if (request.find("settings.html") != string::npos) {
					body = getSettings(player);
				} else {
					body = getHomePage(player);
				}
			} else {
				body = getLoginPage();
			}

			player = NULL;
		}
	}







	if (header == "") {
		header = Server::generateNormalHeader(body.length());
	}



	return (header+"\n\n"+body);


}
